<?php

require_once HGN_CORE_PATH."/hgn_db_common.inc";

/**
 * Add a restaurant into database, $values containing necessary value for the 
 *  res table, plus:
 * - value for the address table, in the format of $value['address']
 * 
 * @return
 *  TRUE on succeed, FALSE on fail.
 */
function hgn_db_restaurant($value,$op = SAVED_NEW){
  $ts = db_transaction();
  
  try{
    if(!isset($value['address']) || !hgn_db_address_record($value['address'],$op)){
      throw new Exception("Saving address error when calling db_restaurant");
    }
    $value['addr_id'] = $value['address']['id'];  // save the saved address id
    
    if(drupal_write_record(HGNT_RESTAURANT, $value) != $op){
      throw new Exception("Error in saving restaurant info.");
    };
    
      // save the uploaded image file for drupal internal db
    $file = file_load($value['image_fid']);
    if($file->status != FILE_STATUS_PERMANENT){ // when this is a newly updated
      $file->status = FILE_STATUS_PERMANENT; // Change status to permanent.
      file_save($file); // Save.
    
      // and record usage so that it won't be deleted easily
      file_usage_add($file, HGN_CORE, 'restaurant', $value['id']);
    }
    
  } catch(exception $e){
    $ts->rollback();
    watchdog("db_exception", $e);
    return FALSE;
  }
  
  return TRUE;
}
